# -*- encoding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution    
#    Copyright (C) 2004-2008 Tiny SPRL (<http://tiny.be>). All Rights Reserved
#    $Id$
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from osv import fields
from osv import osv
import ir

import netsvc
import time
from mx import DateTime

logger = netsvc.Logger()

class stock_picking(osv.osv):
    
    _inherit = 'stock.picking'

    
    def test_assigned(self, cr, uid, ids):
        superResult = super(stock_picking,self).test_assigned(cr, uid, ids)
        #get production order that is related to this picking    
        if superResult:
            mrp_production_obj = self.pool.get('mrp.production') 
            stock_move_obj = self.pool.get('stock.move') 
            prodution_ids = mrp_production_obj.search(cr, uid, [('picking_id', 'in', ids),('expiry_handled','<>','True')])
            for production in  mrp_production_obj.browse(cr,uid,prodution_ids):
                logger.notifyChannel('test_assigned', netsvc.LOG_WARNING, 'production id:%s' %(production.id))
                if production.picking_id.state=='cancel':
                    continue
                for picking_moves in production.picking_id.move_lines:
                   uomFactor=picking_moves.product_uom.factor
                   newSQL = ('''select a.prodlot_id as lotid, a.name as qty,
                                    (select sum(sm.product_qty) from stock_move as sm
                                    where 
                                    sm.prodlot_id = a.prodlot_id and 
                                    sm.location_id = a.location_id  and
                                    sm.location_id <> sm.location_dest_id and
                                    sm.state in ('assigned')
                                    group by sm.prodlot_id) as virtual_qty 
                                from
                                stock_report_prodlots a ,stock_production_lot b  
                                where
                                a.prodlot_id = b.id and
                                a.location_id = %s  and
                                a.product_id =  %s and
                                a.name > 0
                                order by b.expiry_date asc''' %( picking_moves.product_id.property_stock_procurement.id, picking_moves.product_id.id, ))
                                                   
                   

                   logger.notifyChannel('test_assigned', netsvc.LOG_WARNING, 'SQL:%s' %(newSQL))
                   cr.execute(newSQL) 
                   result =cr.fetchall()
                   pickingQty = picking_moves.product_qty
                   remaingQty = pickingQty
                   firstRealTrial =True
                   for (prodLot , lotQtyInBaseUOM, virtual_qty) in result:
                       #if virtual_qty does not exist skip this lot
                       if not virtual_qty:
                           virtual_qty =0
                       lotQty = lotQtyInBaseUOM * uomFactor
                       lotQty = lotQty - virtual_qty
                       if lotQty <= 0 :
                           continue
                       actualRemainingQty = remaingQty
                       remaingQty = remaingQty - lotQty
                       logger.notifyChannel('test_assigned', netsvc.LOG_WARNING, 'actualRemainingQty:%s,remaingQty:%s,prodLot:%s,lotQty:%s, ' %(actualRemainingQty,remaingQty,prodLot,lotQty))
                       if remaingQty <= 0:
                           if firstRealTrial:
                               stock_move_obj.write(cr, uid, [picking_moves.id], {'prodlot_id':prodLot}) 
                               firstRealTrial = False
                           else:
                                newMove = stock_move_obj.copy(cr, uid, picking_moves.id, {'product_qty': actualRemainingQty, 'prodlot_id':prodLot , 'state': 'assigned'})
                           break     
                       else:
                           if firstRealTrial:
                               stock_move_obj.write(cr, uid, [picking_moves.id], { 'product_qty': lotQty , 'prodlot_id':prodLot }) 
                               firstRealTrial = False
                           else:
                                newMove = stock_move_obj.copy(cr, uid, picking_moves.id, {'product_qty': lotQty, 'prodlot_id':prodLot, 'state': 'assigned'})    
                                
                mrp_production_obj.write(cr,uid,[production.id],{'expiry_handled':True })               
        return superResult

		
		
    
stock_picking()
